#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <locale.h>
#include <pthread.h>

#include <minigui/common.h>
#include <minigui/minigui.h>
#include <minigui/gdi.h>
#include <minigui/window.h>
#include <minigui/control.h>
#include <minigui/mgext.h>

#include "gs.h"
#include "init.h"
#include "setup.h"
#include "hctable.h"
#include "mainwindow.h"
#include "scrsaver.h"
#include "gs_controls.h"
#include "dataview.h"

static unsigned int old_tick_count;
static pthread_t pid_scrsaver;

static int deal_msg(void* context, HWND hWnd, int message, WPARAM wParam, LPARAM lParam)
{
    old_tick_count = GetTickCount ();

    if (pid_scrsaver) {
        SendNotifyMessage (hScrSaver, MSG_CLOSE, 0, 0);
        
        ShowCursor (TRUE);
        pid_scrsaver = 0;

        return HOOK_STOP;
    }

    return HOOK_GOON;
}


extern int tscal_win_entry (void);

int MiniGUIMain (int args, const char* arg[])
{
    int ret;
    HWND hMainWnd;
    MSG Msg;
    
    if (!InitMiniGUIExt()) {
        return 2;
    }

	tscal_win_entry();

    if (!RegisterGsControls())
        return -1;
    
    ret = gs_setup_init();
    
    if (ret != 0) {
        /* TODO
         * if it first running, must show system setting dialog 
         */
        
    }
    
    gs_init("/dev/ttyS1");
    //setlocale (LC_COLLATE, "zh_CN");
	
    hMainWnd = GsMainWindow(HWND_DESKTOP);
   // UpdateWindow(hMainWnd, TRUE);

    RegisterKeyMsgHook ((void*)hMainWnd, deal_msg);
    RegisterMouseMsgHook ((void*)hMainWnd, deal_msg);

    while(GetMessage(&Msg, hMainWnd)) {
        if (pid_scrsaver == 0 && GetTickCount () > old_tick_count + 30000) {
            ShowCursor (FALSE);
            ret = pthread_create (&pid_scrsaver, NULL, ScreenSaverMain, NULL);
        }

        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }    

    RegisterKeyMsgHook (NULL, NULL);
    RegisterMouseMsgHook (NULL, NULL);

    MiniGUIExtCleanUp ();
    UnregisterGsControls();

    MainWindowThreadCleanup(hMainWnd);

    PostMessage(HWND_DESKTOP, MSG_ENDSESSION, 0, 0);

    return 0;
}

#ifndef _LITE_VERSION
#include <minigui/dti.c>
#endif
